package com.bnz.dao.impl;

import com.bnz.dao.UserDao;
import com.bnz.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;

@Repository
public class UserDaoImpl implements UserDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Override
    public void add() {
        System.out.println("UserDaoImpl--》add()");
    }

    @Override
    public void update() {
        System.out.println("UserDaoImpl--》update()");
    }

    @Override
    public void delete() {
        System.out.println("UserDaoImpl--》delete()");
    }

    @Override
    public void query() {
        int i = 10 / 0;
        System.out.println("UserDaoImpl--》query()");
    }

    //1. 转账
    @Override
    public void updateUser(int uid, double money) {
        jdbcTemplate.update("update user set balance = balance + ? where uid = ?",money,uid);
    }

    //2. 添加用户
    @Override
    public void addUser(User user) {
        jdbcTemplate.update("insert into user values(null,?,?)",user.getUsername(),user.getBalance());
    }

    //3. 根据id查找用户
    @Override
    public User findById(int id) {
        return jdbcTemplate.queryForObject("select * from user where uid=?",this,id);
    }

    //4. 修改用户
    @Override
    public void update(User user) {
        jdbcTemplate.update("update user set username=?, balance=? where uid=?",
                user.getUsername(),user.getBalance(),user.getUid());
    }
    //5. 删除用户
    @Override
    public void delete(int id) {
        jdbcTemplate.update("delete from user where uid = ?",id);
    }
    // 实现行映射器（将ResultSet转换为User）
    @Override
    public User mapRow(ResultSet rs, int rowNum) throws SQLException {
        return new User(rs.getInt("uid"),
                rs.getString("username"),
                rs.getDouble("balance"));
    }
}
